import axios from 'axios'
import {Message} from "element-ui";
import router from "../router";

/**
 * 响应拦截器
 */
axios.interceptors.response.use(success=>{ //http 响应码200 进入，不是服务端返回的
    if(success.status && success.status == 200 && success.data.status == 500){
        Message.error({message:success.data.msg})
        return; //返回相当于空
    }
    if(success.data.msg){
        Message.success({message:success.data.msg})
    }
    return success.data; //返回数据到请求调用的地方
},error => {//http其他响应码进入
    if(error.response.status == 504 || error.response.status == 404){
        Message.error({message:'服务器被吃了...'})
    }else if (error.response.status == 403){
        Message.error({message:'权限不足，请联系管理员'})
    }else if (error.response.status == 401){
        Message.error({message:'未登录'})
        router.replace('/')
    }else{
        if(error.response.data.msg){
            Message.error({message:error.response.data.msg})
        }else{
            Message.error({message:'未知错误!'})
        }
    }
    return;
})

let base = '';

export const postKeyValueRequest = (url,params)=>{
    return axios({
       method:'post',
       url:`${base}${url}`,
       data:params,
       transformRequest:[function (data) { //这里定义这个，是方便后台登录时候用k:y形式而不是json提交数据
           let ret ='';
           for (let i in data){
               ret += encodeURIComponent(i)+'='+encodeURIComponent(data[i])+'&'
           }
           return ret;
       }],
        header:{
           'ContentType':'application/x-www-form-urlencoded'
        }
    });
};

export const postRequest = (url,params)=>{
    return axios({
        method: 'post',
        url:`${base}${url}`,
        data:params
    })
};

export const putRequest=(url,params)=>{
    return axios({
        method: 'put',
        url:`${base}${url}`,
        data:params
    })
};
export const getRequest=(url,params)=>{
    return axios({
        method: 'get',
        url:`${base}${url}`,
        data:params
    })
};
export const deleteRequest=(url,params)=>{
    return axios({
        method: 'delete',
        url:`${base}${url}`,
        data:params
    })
};


















